<template>
    <div>
        <div>
            <input type="text" v-model="form.host"/>
        </div>
        <div>
            <input type="text" v-model="form.port"/>
        </div>
        <div>
            <input type="text" v-model="form.user"/>
        </div>
        <div>
            <input type="text" v-model="form.password"/>
        </div>
        <div>
            <input type="text" v-model="form.database"/>
        </div>
        <div>
            <button @click="()=>createInit()" v-loading="loading">登录</button>
        </div>
        <div>
            <h3>登录历史</h3>
            <ul style="display: flex;flex-wrap: wrap;list-style: none;">
                <li v-for="item in loginList" style="background: #ddd;cursor: pointer;margin: 5px;" @click="()=>{form=item;$forceUpdate();}">
                    {{item.database}}/{{item.host}}
                </li>
            </ul>
        </div>
    </div>
</template>
<script>
    import {safeParseJson, setCookie} from "../../utils/utils";

    export default {
        data() {
            return {
                loading:false,
                loginList: [],
                form: {
                    host: "localhost",
                    database: "renren_fast",
                    password: "12liumingtai",
                    user: "root",
                    port: "3306",
                },
            };
        },
        mounted(){
            this.ajaxGetConnectList();
        },
        methods: {
            ajaxGetConnectList(){
                axios.get("/databases/connectList").then(res=>res.data).then(res=>{
                    this.loginList=res
                })
            },
            createInit() {
                this.loading=true
                axios.post("/databases/create", {
                    ...this.form
                }).then(res=>res.data).then(res => {
                    debugger
                    this.loading=false
                    //保存登录历史到session中
                    var loginList = safeParseJson(sessionStorage.getItem("loginList")) || []
                    if (loginList.length == 0) {
                        loginList.push(this.form)
                    } else {
                        var index = loginList.findIndex(item => item.database == this.form.database)
                        if (index >= 0) {
                        } else {
                            loginList.push(this.form)
                        }
                    }

                    sessionStorage.setItem("loginList", JSON.stringify(loginList))
                    //保存token  token后台可以解析
                    setCookie("token",res.token)
                    setCookie("currentUser",this.form)
                    setTimeout(() => {
                        location.href = "/"
                    }, 500)

                })
            }
        }
    };
</script>  